﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using TCEasyPrintRev.Models;
using System.Web.Security;
using System.Security.Cryptography;
using System.Text;
using NHibernate.Linq;
using TCEasyPrintRev.WCF_member;

namespace TCEasyPrintRev.Controllers
{
    public class MemberController : Controller
    {
        public ActionResult LogOn()
        {
            return View();
        }

        [HttpPost]
        public ActionResult LogOn(Member model, string returnUrl)
        {
            if (CekEmail(model)!=0)
            {
                FormsAuthentication.SetAuthCookie(model.email, true);
                    
                if ( Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                    && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\") )
                {
                    return Redirect(returnUrl);
                }
                else
                {
                    return RedirectToAction("Index", "Home");
                }
            }
            else
            {
                ModelState.AddModelError("", "The user name or password provided is incorrect.");
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

      
        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(Member model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                model.password = enkripsi.enkrip(model.password);
                model.ID =autoIncrement() ;
                CRUD<Member>.insert(model);
                    
                FormsAuthentication.SetAuthCookie(model.email, false /* createPersistentCookie */);
                return RedirectToAction("Index", "Home");       
            }
            return View(model);
        }

        
        private int CekEmail(Member model)
        {
            model.password = enkripsi.enkrip(model.password);
            return getAll().Where(o=>o.password==model.password && o.email==model.email).ToList().Count;
        }


       


        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";

                case MembershipCreateStatus.InvalidPassword:
                    return "The password provided is invalid. Please enter a valid password value.";

                case MembershipCreateStatus.InvalidEmail:
                    return "The e-mail address provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidAnswer:
                    return "The password retrieval answer provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidQuestion:
                    return "The password retrieval question provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.InvalidUserName:
                    return "The user name provided is invalid. Please check the value and try again.";

                case MembershipCreateStatus.ProviderError:
                    return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                case MembershipCreateStatus.UserRejected:
                    return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator.";

                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion


        public static List<Member> getAll()
        {
            using (var session = CRUD<Member>.load().OpenSession())
            {
                var list = session.QueryOver<Member>().List();

                return list.ToList();
            }
        }

       

       public  static  bool Login(string password, string email)
        {

           
            
            password = enkripsi.enkrip(password);

            using (var session = CRUD<Member>.load().OpenSession())
            {
                int list = session.QueryOver<Member>().List().
                    Where(o => o.password == password&& o.ID == email).ToList().Count();

                if (list != 0) return true; else return false;
            }

        }

       private static string autoIncrement()
       {
           string akhir;
           int angka;
          try{
           using (var session = CRUD<Member >.load().OpenSession())
           {
               akhir = session.QueryOver<Member>().List().Last().ID;


           }

          
               
               string[] x = akhir.Split('M').ToArray(); angka = int.Parse(x[1]) + 1; }

               catch { angka = 1; }

          


           if (angka.ToString().Count() == 1)
               return "M0000" + angka;
           else if (angka.ToString().Count() == 2)
               return "M000" + angka;
           else if (angka.ToString().Count() == 3)
               return "M00" + angka;
           else if (angka.ToString().Count() == 4)
               return "M0" + angka;
           else
               return angka.ToString();
       }

      
       public static void register(MemberS input)
       {
           Member member = new Member(input);
           member.password = enkripsi.enkrip(member.password);
           member.ID = autoIncrement();
           CRUD<Member>.insert(member);
       }
    }
}
